<?php

namespace app\index\service;

use app\common\model\Area;
use app\common\model\ConsultingQuestion;
use app\common\model\LawyerImpression;
use app\index\dao\ConsultingQuestionDao;
use app\index\dao\LawCaseCategoryDao;
use app\index\dao\MemberDao;
use app\index\model\UM as UM;
use think\facade\Config;

/**
 * Class HomeService
 * @package app\home\service
 */
class HomeService
{
    // dao
    private MemberDao $memberDao;
    private LawyerImpressionService $impressionService;
    private LawCaseCategoryDao $categoryDao;
    private ConsultingQuestionDao $consultingQuestionDao;

    public function __construct(LawCaseCategoryDao $categoryDao, MemberDao $memberDao, ConsultingQuestionDao $consultingQuestionDao, LawyerImpressionService $impressionService)
    {
        $this->memberDao = $memberDao;
        $this->impressionService = $impressionService;
        $this->categoryDao = $categoryDao;
        $this->consultingQuestionDao = $consultingQuestionDao;
    }

    /**
     * @param \app\index\model\UM|null $user
     * @param array $params
     * @return array
     */
    public function read(?UM $user, array $params): array
    {
        $userId = $user ? $user->id : 0;
        $cityId = $params['cityId'] ?? null;
        $provinceId = null;

        if (is_id($cityId) && $user) {
            $this->getLocationCityService()->add($user, ['cityId' => $cityId]);
        }

        if (is_id($cityId)) {
            $city = Area::where('id', $cityId)->find();
            if ($city && is_id($city->pid)) {
                $provinceId = $city->pid;
            }
        }

        // 案件类型
        $categories = $this->categoryDao->selectHome(8);
        $categories = array_chunk($categories->all(), 4);

        // 律师
        $lawyers = $this->memberDao->selectLawyersHome($cityId, $provinceId, 4);

        // 记录曝光行为
        $lawyers->each(function ($lawyer) use ($userId) {
            $this->impressionService->insert(LawyerImpression::SHOUYE_YOUXUAN, $lawyer->id, $userId);
        });

        // 热门咨询
        $questions = $this->consultingQuestionDao->selectHome(2);

        // 记录曝光行为
        $questions->each(function (ConsultingQuestion $question) use ($userId) {
            $this->impressionService->insert(LawyerImpression::SHOUYE_REMENZIXUN, $question->lawyerId, $userId);
        });

        // 公众号文章链接
        $subscription = Config::get('site.subscription_article_link', '');

        return [
            'categories' => $categories,
            'lawyers' => $lawyers,
            'questions' => $questions,
            'subscription' => $subscription,
        ];
    }

    private function getLocationCityService(): LocationCityService
    {
        return app(LocationCityService::class);
    }
}
